<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-16
 * Time: 上午8:57
 */
namespace Home\Controller;
use Think\Controller;
use User\Api\UserApi;
class UserController extends CommonController {
    /**
     * 用户基本信息修改  2016.6.17 teng
     */
    public function index()
    {
        if(IS_POST){
            $data         = I('post.');
            $user_type    = $data['user_type'];
            $data['uid']  = UID;
            $data['type'] = 1;
            if($data['id'])
            {
                $uid    = D('UserInfo')->userUpdate($data);  //信息验证
            }
            else
            {
                $uid    = D('UserInfo')->UserAdd($data);  //信息验证
            }
            if($uid>0)
            {
                $id = session('user_auth.uid');
                action_log('modify_information','user',$id, $id);
                if($user_type == 1){
                    $this->success('操作成功',U('Task/a_add',array('user_type'=>1)));
                }else{
                    $this->success('操作成功');
                }
            }
            else
            {
                $this->error($this->showRegError($uid));
            }
        }else{
            $where['uid']    = UID;
            $list   = M('UserInfo')->where($where)->select();
            $this->assign('_list',$list);

            $this->assign('meta_title','用户基本信息');
            $this->display();
        }
    }
    /**
     * jquery获取基本信息
     * 2016.6.5 teng
     */
    public function user_info ()
    {
        if(I('id')){
            $where['id']     = I('id');
            $where['uid']    = UID;
            $where['type']   = 1;
            $user            = M('UserInfo')->where($where)->find();
            $this->ajaxReturn($user);
        }
    }
    /**
     * jquery获取默认的个人地址
     * 2016.6.6 teng
     */
    public function user_default ()
    {
        //默认个人资料里的委托单位和通用地址
        $info_user_default = M('User')->find(UID);
        if($info_user_default){
            $this->assign('info_user_default',$info_user_default);
        }
        $this->ajaxReturn($info_user_default);
    }

    /**
     * jquery获取缴费方式
     * 2016.6.5 teng
     */
    public function user_payment ()
    {
        if(I('id')){
            $where['id']     = I('id');
            $where['uid']    = UID;
            $where['type']   = 2;
            $user            = M('UserInfo')->where($where)->find();
            $this->ajaxReturn($user);
        }
    }

    /**
     * 用户基本信息修改
     * 2016.5.30 teng
     */

    public function deal_info ($data,$type)
    {
        if($type==1) {
            $array  =$this->prove_array();
            foreach ($array as $key => $vo) {   //信息验证
                if ($data[$vo['title']] == $vo['value']) {
                    $result['result'] = 0;
                    $result['msg'] = $vo['msg'];
                    $this->ajaxReturn($result);
                }
                if ($vo['value'] == 'int') {
                    if (!preg_match("/(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)/", $data[$vo['title']])) {
                        $result['result'] = 0;
                        $result['msg'] = $vo['msg'];
                        $this->ajaxReturn($result);
                    }
                }
                if ($vo['value'] == 'email') {
                    if (!preg_match('/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/', $data[$vo['title']])) {
                        $result['result'] = 0;
                        $result['msg'] = $vo['msg'];
                        $this->ajaxReturn($result);
                    }
                }
                $vo = addslashes(trim($vo));
            }
        }else{
            if($data['fkfs']=='' || $data['dwsh']=='' || $data['qbfs']==''){
                $result['result']   = 0;
                $result['msg']      = '信息填写不完整';
                $this -> ajaxReturn($result);
            }
            if($data['fkfs']==2 && $data['upload_ids']==''){
                $result['result']   = 0;
                $result['msg']      = '请选择上传图片';
                $this -> ajaxReturn($result);
            }
            if($data['dwsh']==2 && $data['kpdw']==''){
                $result['result']   = 0;
                $result['msg']      = '请填写发票抬头';
                $this -> ajaxReturn($result);
            }
            if($data['qbfs']==2 && $data['kddz']==''){
                $result['result']   = 0;
                $result['msg']      = '请填写收件地址';
                $this -> ajaxReturn($result);
            }
        }
        $model = M('UserInfo');
        $arr   = $model->create($data);
        if($data['id']){    //修改个人信息
            $where['id']    = $data['id'];
            $where['uid']   = UID;
            $id = $model->where($where)->save($arr);
        }else{              //添加
            $arr['uid']  = UID;
            $arr['type'] = $type;
//            print_r($arr);die;
            $id          = $model->add($arr);
        }
        return $id;
    }
    /**
     * 用户基本信息删除
     * 2016.5.30 teng
     */
    public function del_user (){
        $sign = I("request.sign");
        if($sign == 'del_user'){
            $model = M('UserInfo');
            $where['uid']   = UID;
            $where['id']    = I('id');
            if($model->where($where)->find()){
                if($model->where($where)->delete()){
                    $result['result'] = 1;
                }else{
                    $result['result']   = 0;
                    $result['msg']      = '删除失败';
                }
            }else{
                $result['result']   = 0;
                $result['msg']      = '信息不存在';
            }
            $this->ajaxReturn($result);

        }
    }
    /**
     * 缴费方式管理
     * 2016.5.30 teng
     */
    public function payment(){
        if(IS_POST){
            $data       = I('info');
            $user_type  = $data['user_type'];
            $id = $this -> deal_info($data,2);
            if($id){
                $id = session('user_auth.uid');
                action_log('modify_information','user',$id, $id);
                $result['result']    = 1;
                $result['user_type'] = $user_type;
                $this -> ajaxReturn($result);
            }else{
                $result['result']   = 0;
                $result['msg']      = '操作失败';
                $this -> ajaxReturn($result);
            }
        }else{
            $where['uid']    = UID;
            $where['type']   = 2;
            $list   = M('UserInfo')->where($where)->select();
            if(I('id')){
                $where['id']     = I('id');
                $user            = M('UserInfo')->where($where)->find();
                $upload_ids_arr  = explode(',',$user['upload_ids']);
                $this->assign('upload_ids_arr',$upload_ids_arr);
                $this->assign('user',$user);
            }
            $this->assign('_list',$list);
            $this->assign('meta_title','用户基本信息');
            $this->display();
        }
    }

    /*
     * 修改用户密码
     */
    public function changePwd(){
        if(UID) {
            $arr = I('pwd');
            foreach($arr as $key=>$vo){
                $vo=addslashes(trim($vo));
            }
            $password = $arr['old'];
            if (!$this->checkpwd($password)) {
                $result['result']   = 0;
                $result['msg']      = '原始密码输入不正确';
                $this->ajaxReturn($result);
            }
            $data['password'] = $arr['pwd'];
            if (!$this->sec_check($data['password'])) {
                $result['result']   = 0;
                $result['msg']      = '原始密码和新密码不能一样';
                $this->ajaxReturn($result);
            }
//            empty($data['password']) && $this->error('请输入新密码');
            $repassword = $arr['repwd'];
//            empty($repassword) && $this->error('请输入确认密码');
            if(strlen($data['password'])<6 || strlen($password)>20)
            {
                $result['result']   = 0;
                $result['msg']      = '密码只允许在6-20位';
                $this->ajaxReturn($result);
            }
            if ($data['password'] !== $repassword) {
                $result['result']   = 0;
                $result['msg']      = '两次输入的密码不一样';
                $this->ajaxReturn($result);
            }
            $data['password'] = md5($data['password']);
            $user = M('User');
            $res = $user->where('id='.UID)->save($data);
            if ($res) {
                $id = session('user_auth.uid');
                action_log('user_changePassword', 'user', $id, $id);
                $result['result'] = 1;
//                $this->success('密码已经修改成功',__APP__.'/Home/User/logout');
                $this->ajaxReturn($result);
            } else {
                $result['result']   = 0;
                $result['msg']      = '密码修改失败';
                $this->ajaxReturn($result);
            }
        }
    }


    /**
     * jquery修改用户信息
     */
    public function changeInfo(){
        $where['id']     = UID;
        $info = M('User')->where($where)->find();
        $this -> ajaxReturn($info);
    }
    /**
     * 修改用户信息
     */
    public function changeInfo_user(){
        if(UID){
            //记录cookie
            $where['id']     = UID;
            $model           = M("User");
            $data            = $_POST;
            foreach($data as $key=>$vo){
                $vo = addslashes(trim($vo));
            }
            if(strlen($data['name'])>100){
                $this->error('名称不能多于100个字符');
            }
            if(!preg_match('/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/',$data['tel'])){
                $this->error('请填写正确联系方式');
            }
            if(!preg_match('/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/',$data['email'])){
                $this->error('请填写正确邮箱');
            }
            if(strlen($data['company'])>255){
                $this->error('委托单位不能多于255个字符');
            }
            if(strlen($data['address'])>255){
                $this->error('通讯地址不能多于255个字符');
            }
            if(strlen($data['user_yqfx'])>255){
                $this->error('研究方式多于255个字符');
            }
            $info            = $model -> where('email="'.$data['email'].'" and id!='.UID) -> find();
            if($info){
                $this->error('邮箱不能重复');
            }
            if($model->where($where)->save($data)){
                $result['result'] = 1;
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }

    }


    /**
     *上传
     */
    public function upload(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $tmp_can	=	$_GET['can']?$_GET['can']:0;
        if($tmp_can==1){
            $upload->exts      =     array('jpg','png','jpeg','gif','bmp');// 设置附件上传类型
        }else{
            $upload->exts      =     array('doc', 'rar','zip','docx');// 设置附件上传类型
        }
        $upload->rootPath  =     './uploads/user/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $tmp_name	=	$_GET['tmp_name'];

        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            echo json_encode(array('state'=>$upload->getError()));
        }else{// 上传成功
            //print_R($info);exit;
            $file=array(
                'uid'=>UID,
                'title'=>$info[$tmp_name]['name'],
                'title_r'=>$info[$tmp_name]['savename'],
                'type'=>'1',
                'size'=>$info[$tmp_name]['size'],
                'dir'=>$upload->rootPath.$info[$tmp_name]['savepath'],
                'create_time'=>date('Y-m-d h:i:s')
            );
            $id = M('Attachment')->add($file);
            echo json_encode(array('state'=>'ok','upload_id'=>$id,'base_file_n'=>$file['title']));
        }
    }

    /**
     *下载
     */
    public function down_file(){
        $file_id=think_decrypt(intval(trim($_GET['file_id'])));
        echo think_encrypt(447);
        echo think_decrypt('MDAwMDAwMDAwMMh1bqE');die;
        if(empty($file_id)){
            redirect("文件不存在跳转页面");
        }else{//如果要加登录条件，这里可以自己加
            $map['id'] = $file_id;
            $list=D('Attachment')->where($map)->select();
            if ($list == false) {//文件不存在，可以跳转到其它页面
                header('HTTP/1.0 404 Not Found');
                header('Location: .');
            } else {
                $file_name="./".$list[0]['dir'].$list[0]['title_r'];//需要下载的文件
                $file_name=iconv("utf-8","gb2312","$file_name");
                if(file_exists($file_name)){
                    $fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
                    if(!file_exists($file_name)){//判断文件是否存在
                        $this->error('文件不存在！');
                    }
                    $file_size=filesize($file_name);//判断文件大小
                    //返回的文件
                    Header("Content-type: application/octet-stream");
                    //按照字节格式返回
                    Header("Accept-Ranges: bytes");
                    //返回文件大小
                    Header("Accept-Length: ".$file_size);
                    //弹出客户端对话框，对应的文件名
                    Header("Content-Disposition: attachment; filename=".$list[0]['title']);
                    //防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
                    $buffer=1024;
                    while(!feof($fp)){
                        $file_data=fread($fp,$buffer);
                        echo $file_data;
                    }
                    //关闭文件
                    fclose($fp);
                }else{
                    $this->error('文件不存在！');
                }

            }
        }
    }


    //检查密码输入的是否正确
    private function checkPwd($pwd){
        $map['id'] = UID;
        $user = M('User');
        $check = $user->find(UID);
        if($check['password'] === md5($pwd)){
            return true;
        }else{
            return false;
        }
    }

    //验证密码是否与旧密码相同
    private function sec_check($newPassword){
        $user = M('User');
        $check = $user->find(UID);
        if($check['password'] === md5($newPassword)){
            return false;
        }else{
            return true;
        }
    }

    //获取用户操作错误相关信息
    private function showError($code=0){
        switch($code){
            case -1:
                $error = "用户名长度不合法";
                break;
            case -3:
                $error = "用户名被占用";
                break;
            case -4:
                $error = "邮箱已经存在";
                break;
            default:
                $error = '未知错误';
        }
        return $error;
    }

    public function logout(){
        if(is_login()){
            $id = session('user_auth.uid');
            action_log('user_logout','user',$id,$id);
            D('User')->logout();
			
			//退出统一身份登录
			Vendor('CAS.source.CAS'); 
			$phpCAS = new \phpCAS();
			$phpCAS::client(CAS_VERSION_2_0,'cas.jalis.nju.edu.cn',443,'cas');
			$phpCAS::setNoCasServerValidation();
			$phpCAS::forceAuthentication();
			$param=array("service"=>"http://kjcx.jalis.nju.edu.cn/index.php/Home/Desk/index.html");//退出登录后返回
			$phpCAS::logout($param);
			
            $this->redirect('Desk/index');
        }else{
            $this->redirect('login');
        }
    }

    /**
     *设为默认值 2016.6.7  teng
    */
    public function default_value ()
    {
        $type   = intval(I('type'));
        if($type)
        {
            $data['default']    = 2;
            $where['uid']       = UID;
            $where['type']      = $type;
            M('UserInfo')->where($where)->save($data);
            $where['id']        = intval(I('id'));
            $data['default']    = 1;
            $list = M('UserInfo')->where($where)->save($data);
            if($list)
            {
                $result['result']   = 1;
            }
            else
            {
                $result['result']   = 0;
                $result['msg']      = '设置失败';
            }
        }
        else
        {
            $result['result']   = 0;
            $result['msg']      = '参数错误';
        }
        $this->ajaxReturn($result);
    }


    /**
     * 验证数组  2016.6.8 teng
     */
    protected function prove_array()
    {
        $array = array(
            array('title'=>'wtrname',       'value'=>'',       'msg'=>'请填写委托人姓名'),
            array('title'=>'wtrphone',      'value'=>'int',     'msg'=>'请填写正确委托人号码'),
            array('title'=>'lxrname',       'value'=>'',       'msg'=>'请填写联系人姓名'),
            array('title'=>'phone',         'value'=>'int',     'msg'=>'请填写正确联系方式'),
            array('title'=>'wtremail',      'value'=>'email',   'msg'=>'请填写正确邮箱'),
            array('title'=>'wtdw',          'value'=>'',       'msg'=>'请填写委托单位'),
            array('title'=>'txdz',          'value'=>'',       'msg'=>'请填写通讯地址'),
        );
        return $array;
    }

    /**
     * 验证数组  2016.6.17 teng
     */
    private function showRegError($code = 0)
    {
        switch ($code) {
            case -1:  $error = '项目长度必须在1-255的字符以内！'; break;
            case -2:  $error = '项目名被占用！'; break;
            case -3:  $error = '委托人姓名必须在1-15的字符以内！'; break;
            case -4:  $error = '请输入正确的委托人号码！'; break;
            case -5:  $error = '联系人姓名必须在1-15的字符以内！'; break;
            case -6:  $error = '请输入正确的联系人号码！'; break;
            case -7:  $error = '委托单位必须在1-255的字符以内！'; break;
            case -8:  $error = '通讯地址必须在1-255的字符以内！'; break;
            case -9:  $error = '邮箱格式不正确！'; break;
            case -10: $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -11: $error = '请选择查新目的！'; break;
            case -12: $error = '请选择项目级别！'; break;
            case -13: $error = '请填写查新点！'; break;
            case -14: $error = '请填写技术要求'; break;
            case -15: $error = '请选择查新要求'; break;
            case -16: $error = '请输入正确完成日期'; break;
            case -17: $error = '请填写中文检索词'; break;
            case -18: $error = '请选择缴费方式'; break;
            case -19: $error = '请选择是否需要发票'; break;
            case -20: $error = '请选择报告领取'; break;
            case -21: $error = '添加任务失败'; break;
            case -22: $error = '更新任务失败'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }
}